package huizhi.net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ServerFileDownload {
    public static void main(String[] args) throws Exception{
        // 启动服务端，监听8888端口
        ServerSocket server = new ServerSocket(8880);
        // 服务端待命，等待客户端连接。在套接字连接之前，都处于阻塞状态
        Socket accept = server.accept();
        BufferedReader buffr = new BufferedReader(new InputStreamReader(accept.getInputStream()));
        //获取字节输出流
        OutputStream outputStream = accept.getOutputStream();
        String value = buffr.readLine();
        //本地路径
        String bendimulu = "D:\\CodeAll\\code\\ExerciseMaven";
        //定义个集合存储查到的路径
        List<String> array = new ArrayList<>();
        //判断是否存在
        search(bendimulu,value,array);
        //获取输入流
        int l ;
        byte[] buffer = new byte[1024];
        if (array.size()>0){
            System.out.println("文件存在");
            outputStream.write("fil".getBytes());
            //获取该文件的输入流
            FileInputStream fileInputStream = new FileInputStream(array.get(0));
            while (-1!=(l=fileInputStream.read(buffer))){
                outputStream.write(buffer,0,l);
            }
        }else {
            System.out.println("文件不存在");
            outputStream.write("msg".getBytes());
        }
        buffr.close();
        outputStream.close();
        accept.close();
        server.close();

    }
    public static void search(String url,String v,List<String> arr){
        File file = new File(url);
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isFile()){
                if (file1.getName().equals(v)){
                    arr.add(file1.getAbsolutePath());
                }
            }else {
                search(file1.getAbsolutePath(),v,arr);
            }
        }
    }
}
